package com.itsv.cyzx.util;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.itsv.xhyy.R;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;


public class LoadImageAysnc {

	// 图片缓存软引用
	private HashMap<String, SoftReference<Drawable>> imageCache;
	// 线程池
	private BlockingQueue<Runnable> queue;
	private ThreadPoolExecutor executor;
	private FileOperator fileOperator;
	private Context context;

	public LoadImageAysnc(Context context) {

		imageCache = new HashMap<String, SoftReference<Drawable>>();
		fileOperator = new FileOperator();
		queue = new LinkedBlockingQueue<Runnable>();
		executor = new ThreadPoolExecutor(1, 5, 180, TimeUnit.SECONDS, queue);
		this.context = context;

	}

	// 异步加载图片的方法（其实可以以任何形式得到图片）
	public Drawable loadImage(final String id, final String wangluoSrc,
			final String bendiSrc, final ImageCallBack imageCallBack) {
		// 如果有缓存则使用缓存中的图片
		if (imageCache.containsKey(id)) {
			SoftReference<Drawable> softReference = imageCache.get(id);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				System.out.println("缓存数据");
				return drawable;
			}
		}
		// 图片加载完成
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Drawable drawable = (Drawable) msg.obj;
				// 图片加载完成的回调函数，用于更新imageview
				imageCallBack.imageLoaded(drawable, wangluoSrc);
			}
		};
		Drawable drawable = null;
		drawable = loadImageFromLocalStorage(bendiSrc); // 如果本地有图片则直接读取
		if (drawable == null) {
			// 异步图片下载方法
			executor.execute(new Runnable() {

				@Override
				public void run() {

					Drawable drawable = null;
					if (drawable == null) {
						try {
							drawable = loadImageFromUrl(wangluoSrc); // 本地读取图片
							fileOperator.write2SDFromInput("zx/", id + ".jpg",
									drawable);
						} catch (Exception e) {
							BitmapDrawable bd = new BitmapDrawable(
									BitmapFactory.decodeResource(
											context.getResources(),
											R.drawable.personal_card_avatar_defult));
							drawable = (Drawable) bd;
							e.printStackTrace();
						}
					}
					imageCache.put(id, new SoftReference<Drawable>(drawable));
					Message msg = handler.obtainMessage(0, drawable);
					msg.sendToTarget();

				}
			});
		} else {
			imageCache.put(id, new SoftReference<Drawable>(drawable));
			Message msg = handler.obtainMessage(0, drawable);
			msg.sendToTarget();
		}

		return drawable;
	}

	// 网络图片下载方法
	public Drawable loadImageFromUrl(String url) throws Exception {
		Drawable d = Drawable.createFromStream(getInputStream(url), "src");
		return d;
	}

	// 本地图片加载方法
	public Drawable loadImageFromLocalStorage(String fileName) {
		Drawable d = fileOperator.readFromSD2Output(fileName);
		return d;
	}

	// 得到网上下载的图片数据流
	public InputStream getInputStream(String url) throws Exception {
		URL m;
		InputStream i = null;
		m = new URL(url);
		i = (InputStream) m.getContent();
		return i;
	}

	// 回调接口
	public interface ImageCallBack {
		public void imageLoaded(Drawable drawable, String iconSrc);
	}
}
